# #!/usr/bin/env python

"""这是消费者终端，由信道来主动推送消息"""
import pika
from rabbitmq_receive.setting import *
from multiprocessing import Process,Pool
import time
import os

class Receiver(object):
    def __init__(self):
        self.__host = HOST
        self.__port = PORT
        self.__queuename = QUEUENAME
        self.__exchangename = EXCHANGE
        self.__rout = ROUT_KEY
        self.__username = USERNAME
        self.__passwd = PASSWD
        self.__exchange_type = EXCHANGE_TYPE
        self.connection = self._connect_rabbitmq()

    # 连接mq队列
    def _connect_rabbitmq(self):
        # 添加用户名和密码
        credentials = pika.PlainCredentials(self.__username, self.__passwd)
        # 配置连接参数
        parameters = pika.ConnectionParameters(host=self.__host, credentials=credentials)
        # 创建一个连接对象
        connection = pika.BlockingConnection(parameters)
        return connection

    def exchange_channel(self,channel):
        # 声明队列
        channel.queue_declare(queue=self.__queuename, durable=True)
        # 声明交换机
        channel.exchange_declare(exchange=self.__exchangename,
                                 exchange_type=self.__exchange_type)
        channel.queue_bind(queue=self.__queuename,
                           exchange=self.__exchangename,
                           routing_key=self.__queuename)

    # 订阅消息
    def consume_message(self):
        channel = self.connection.channel()
        self.exchange_channel(channel)
        # 公平调度，最多推送5个
        channel.basic_qos(prefetch_count=5)
        # 订阅消息
        channel.basic_consume(self.callback,
                              queue=self.__queuename,
                              no_ack=False)
        while True:
            try:
                # 循环等待
                channel.start_consuming()
            except Exception as e:
                print(e)

    # 接收消息
    def callback(self,ch, method, properties, body):
        # 发送确认
        ch.basic_ack(delivery_tag=method.delivery_tag)
        print("this is %s" % body)
        print(os.getpid())


if __name__ == '__main__':
    receive = Receiver()
    receive.consume_message()



